package com.hmall.item.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.constatnts.MqConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 分页查询商品
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> getByPage(@RequestParam("page") Integer page, @RequestParam("size") Integer size) {
        Page<Item> page1 = new Page<>(page, size);
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        itemService.page(page1, queryWrapper);
        PageDTO<Item> dto = new PageDTO<>(page1.getTotal(),page1.getRecords());
        return dto;
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item getById(@PathVariable("id") Long id) {
        return itemService.getById(id);
    }

    /**
     * 新增商品
     * @param item
     * @return
     */
    @PostMapping
    public void save(@RequestBody Item item) {
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        item.setStatus(2);
        itemService.save(item);

        rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE,MqConstants.HOTEL_INSERT_KEY,item.getId());
    }

    /**
     * 商品上架、下架
     * @param id
     * @param status
     * @return
     */
    @PutMapping("/status/{id}/{status}")
    public void updatastatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        itemService.
        update().set("status",status).eq("id",id).update();

        rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE,MqConstants.HOTEL_INSERT_KEY,id);
    }

    /**
     * 修改商品
     * @param item
     */
    @PutMapping
    public void updata(@RequestBody Item item){
        itemService.updateById(item);

        rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE,MqConstants.HOTEL_INSERT_KEY,item.getId());
    }

    /**
     * 根据id删除商品
     * @param id
     */
    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id")Long id){
         itemService.removeById(id);

        rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE,MqConstants.HOTEL_DELETE_KEY,id);
    }
}
